package com.wr.modules.system.controller;

import com.wr.common.core.constants.UserConstants;
import com.wr.common.core.result.R;
import com.wr.common.core.utils.BeanUtils;
import com.wr.common.core.utils.StringUtils;
import com.wr.common.security.utils.SecurityUtils;
import com.wr.modules.system.domain.sys.menu.SysMenu;
import com.wr.modules.system.domain.sys.menu.SysMenuVo;
import com.wr.modules.system.domain.sys.vo.RouterVo;
import com.wr.modules.system.domain.sys.vo.TreeSelect;
import com.wr.modules.system.service.ISysMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author MyPC
 */
@Tag(name = "B - 菜单管理接口")
@RestController
@RequestMapping("/sys-menu")
public class SysMenuController {

    @Autowired
    private ISysMenuService iSysMenuService;

    @Operation(summary = "查询菜单列表")
    @GetMapping("/list")
    public R<List<SysMenuVo>> list(SysMenuVo menu) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenuVo> menus = iSysMenuService.selectMenuList(menu, userId);
        return R.ok(menus);
    }

    @Operation(summary = "获取菜单详情")
    @GetMapping(value = "/info/{menuId}")
    public R<SysMenuVo> getInfo(@PathVariable Long menuId) {
        return R.ok(BeanUtils.copyDataProp(iSysMenuService.getById(menuId), new SysMenuVo()));
    }

    @Operation(summary = "获取菜单下拉树表")
    @GetMapping("/treeselect")
    public R<List<TreeSelect>> treeselect(SysMenuVo menu) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenuVo> menus = iSysMenuService.selectMenuList(menu, userId);
        return R.ok(iSysMenuService.buildMenuTreeSelect(menus));
    }

    @Operation(summary = "加载对应角色菜单列表树")
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public R<Map<String, Object>> roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenuVo> menus = iSysMenuService.selectMenuList(userId);
        Map<String, Object> map = new HashMap<>(2);
        map.put("checkedKeys", iSysMenuService.selectMenuListByRoleId(roleId));
        map.put("menus", iSysMenuService.buildMenuTreeSelect(menus));
        return R.ok(map);
    }

    @Operation(summary = "添加菜单")
    @PostMapping("/add")
    public R<Boolean> add(@Validated @RequestBody SysMenuVo menu) {
        if (!iSysMenuService.checkMenuNameUnique(BeanUtils.copyDataProp(menu, new SysMenuVo()))) {
            return R.fail("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return R.fail("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        SysMenu sysMenu = BeanUtils.copyDataProp(menu, new SysMenu());
        sysMenu.setCreateBy(SecurityUtils.getUserId().toString());
        return R.ok(iSysMenuService.save(sysMenu) > 0);
    }

    /**
     * 修改菜单
     */
    @Operation(summary = "修改菜单")
    @PutMapping("/edit")
    public R<Boolean> edit(@Validated @RequestBody SysMenuVo menu) {
        if (!iSysMenuService.checkMenuNameUnique(BeanUtils.copyDataProp(menu, new SysMenuVo()))) {
            return R.fail("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) {
            return R.fail("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return R.fail("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        SysMenu sysMenu = BeanUtils.copyDataProp(menu, new SysMenu());
        sysMenu.setCreateBy(SecurityUtils.getUserId().toString());
        return R.ok(iSysMenuService.update(sysMenu) > 0);
    }

    @Operation(summary = "删除菜单")
    @DeleteMapping("/remove/{menuId}")
    public R<Boolean> remove(@PathVariable("menuId") Long menuId) {
        if (iSysMenuService.hasChildByMenuId(menuId)) {
            return R.warn("存在子菜单,不允许删除");
        }
        if (iSysMenuService.checkMenuExistRole(menuId)) {
            return R.warn("菜单已分配,不允许删除");
        }
        return R.ok(iSysMenuService.deleteById(menuId)>0);
    }

    @Operation(summary = "获取菜单路由信息")
    @GetMapping("/getRouters")
    public R<List<RouterVo>> getRouters() {
        List<SysMenuVo> menus = iSysMenuService.selectMenuTreeByUserId();
        return R.ok(iSysMenuService.buildMenus(menus));
    }
}
